package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.District;
import com.ruitaowang.core.domain.SysUser;
import com.ruitaowang.core.domain.UserMembers;
import com.ruitaowang.core.domain.UserMembersVO;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.DistrictService;
import com.ruitaowang.goods.service.UserMembersService;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/15.
 */
@RestController
public class APIUserMembersController extends BaseController {
    @Autowired
    private UserMembersService userMembersService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private DistrictService districtService;


    /**
     * @api {get} /api/admin/members 后台管理-会员管理-会员期限-分页获取用户会员列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/members
     *
     * @apiName findUserMembersPage
     * @apiGroup UserMembers
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "comsumerId": 0,
     *                   "consumer": 0,
     *                   "ctime": 1503327977673,
     *                   "endTime": "2018-08-21",
     *                   "memberId": 282,
     *                   "memberType": 1,
     *                   "mtime": 1503327977673,
     *                   "remark": "爱英美教育",
     *                   "rstatus": 0,
     *                   "startTime": "",
     *                   "userId": 63268
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/members"
     *  }
     */
    @RequestMapping("/api/admin/members")
    public String findUserMembersPage(UserMembers userMembers, int page) {
        userMembers.setPage(page);
        if(!ObjectUtils.isEmpty(userMembers.getSidx())){
            userMembers.setOrderBy(userMembers.getSidx() + " " + userMembers.getSord() + "," + userMembers.getOrderBy());
        }
        List<UserMembers> list = userMembersService.selectForPage(userMembers);
        for (UserMembers where : list) {
            where.setRemark(sysUserService.selectByPK(where.getUserId()).getNickname());
        }
        MsgOut o = MsgOut.success(list);
        o.setRecords(userMembers.getRecords());
        o.setTotal(userMembers.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/members/phone 后台管理-会员管理-会员期限-dataformatter查询用户电话
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/members/phone
     *
     * @apiName userMemberPhone
     * @apiGroup UserMembers
     *
     * @apiParam {long} userId 用户ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *           "code": 0,
     *           "data": {
     *                   "ctime": 1500533328587,
     *                   "department": "",
     *                   "email": "",
     *                   "headimgurl": "http://wx.qlogo.cn/mmhead/Q3auHgzwzM4YaNNwZlxcOIGfFfaXwsOjMVYAw37FoDLQib2m4GamXVg/0",
     *                   "id": 63179,
     *                   "idCard": "",
     *                   "lastIp": "114.242.250.187",
     *                   "lastTime": 1500533386353,
     *                   "locked": false,
     *                   "mtime": 1500533328587,
     *                   "nickname": "柠檬",
     *                   "password": "$2a$10$gkOmLdCBDpH09UlgcabSx.0xvjrm0Wcf30DNGHz/Fp83CLeqbVuSa",
     *                   "phone": "18600976475",
     *                   "position": "",
     *                   "qrimgurl": "http://static.ruitaowang.com/qr/qr_63179.png",
     *                   "realName": "",
     *                   "remark": "",
     *                   "rstatus": 0,
     *                   "userType": 0,
     *                   "username": "18600976475"
     *                  },
     *           "msg": "操作成功啦",
     *           "title": "成功",
     *           "type": "SUCCESS"
     *     }
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/members/phone"
     *  }
     */
    @RequestMapping("/api/admin/members/phone")
    public String userMemberPhone(Long userId) {
        SysUser sysUser = sysUserService.selectByPK(userId);
        MsgOut o = MsgOut.success(sysUser);
        return this.renderJson(o);
    }

    /**
     * @api {post} /api/admin/members 后台管理-会员管理-会员期限-注册各类会员信息
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/members
     * @apiPermission admin
     *
     * @apiName createUserMember
     * @apiGroup UserMembers
     *
     * @apiParam {int} userId 用户ID.
     * @apiParam {byte} memberType 会员类型.
     * @apiParam {string} remark 备注.
     * @apiParam {string} endTime 会员结束时间.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "comsumerId": 0,
     *                   "consumer": 0,
     *                   "ctime": 1503327977673,
     *                   "endTime": "2018-08-21",
     *                   "memberId": 282,
     *                   "memberType": 1,
     *                   "mtime": 1503327977673,
     *                   "remark": "爱英美教育",
     *                   "rstatus": 0,
     *                   "startTime": "",
     *                   "userId": 63268
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/members"
     *  }
     */

    @RequestMapping(value = "/api/admin/members", method = RequestMethod.POST)
    public String createUserMember(UserMembers userMembers) {
        userMembersService.insert(userMembers);
        MsgOut o = MsgOut.success(userMembers);
        return this.renderJson(o);
    }

    /**
     * 区域代理商入住
     * @param userMembers
     * @param districtId
     * @return
     */
    @RequestMapping(value = "/api/wap/members/district", method = RequestMethod.POST)
    public String createUserMemberDistrict(UserMembers userMembers,Long districtId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(userMembers)){
            return this.renderJson(MsgOut.error("参数错误"));
        }
        Map out=new HashMap();

        userMembers.setUserId(user.getId());
        userMembersService.insert(userMembers);

        District district=districtService.selectByPK(districtId);

        if (ObjectUtils.isEmpty(district)){
            return this.renderJson(MsgOut.error("参数错误"));
        }
        district.setCityUserId(user.getId());
        district.setInitial(userMembers.getEndTime());
        districtService.update(district);

        out.put("district",district);
        out.put("userMembers",userMembers);

        MsgOut o = MsgOut.success(out);
        return this.renderJson(o);
    }
    /**
     * @api {put} /api/admin/members 后台管理-会员管理-会员期限-修改各类会员信息
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/members
     * @apiPermission admin
     *
     * @apiName updateUserMember
     * @apiGroup UserMembers
     *
     * @apiParam {int} userId 用户ID.
     * @apiParam {byte} memberType 会员类型.
     * @apiParam {string} remark 备注.
     * @apiParam {string} endTime 会员结束时间.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "comsumerId": 0,
     *                   "consumer": 0,
     *                   "ctime": 1503327977673,
     *                   "endTime": "2018-08-21",
     *                   "memberId": 282,
     *                   "memberType": 1,
     *                   "mtime": 1503327977673,
     *                   "remark": "爱英美教育",
     *                   "rstatus": 0,
     *                   "startTime": "",
     *                   "userId": 63268
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/members"
     *  }
     */
    @RequestMapping(value = "/api/admin/members", method = RequestMethod.PUT)
    public String updateUserMember(UserMembers userMembers) {
        userMembersService.update(userMembers);
        MsgOut o = MsgOut.success(userMembers);
        return this.renderJson(o);
    }

    /**
     * @api {delete} /api/admin/members/{userId} 后台管理-会员管理-会员期限-删除会员信息
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/members
     * @apiPermission admin
     *
     * @apiName deleteUserMember
     * @apiGroup UserMembers
     *
     * @apiParam {int} userId 用户ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":1,
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/members/{userId}"
     *  }
     */

    @RequestMapping(value = "/api/admin/members/{userId}", method = RequestMethod.DELETE)
    public String deleteUserMember(@PathVariable("userId") Long userId) {
        MsgOut o = MsgOut.success(userMembersService.delete(userId));
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/userMember/excel/{userId} 后台管理-会员管理-会员期限-excel导出
     * @apiVersion 0.1.0
     * @apiName adminUserMemberExcel
     * @apiGroup UserMembers
     *
     * @apiParam {long} userId 用户ID.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/userMember/excel/{userId}"
     *  }
     */

    @RequestMapping("/api/admin/userMember/excel/{userId}")
    public void adminUserMemberExcel(@PathVariable("userId") Long userId) {
        SysUser sysUser = sysUserService.selectByPK(userId);
        List<UserMembersVO> list = new ArrayList<>();
        UserMembers userMembers = new UserMembers();
        userMembers.setUserId(userId);
        List<UserMembers> userMembersList = userMembersService.select(userMembers);
        for (UserMembers where : userMembersList) {
            UserMembersVO userMembersVO = new UserMembersVO();
            BeanUtils.copyProperties(where,userMembersVO);
            userMembersVO.setRemark(sysUser.getNickname());
            userMembersVO.setPhoneVO(sysUser.getPhone());
            switch (where.getMemberType()) {
                case 0:
                    userMembersVO.setMemberTypeVO("快省-龙蛙会员");
                    break;
                case 1:
                    userMembersVO.setMemberTypeVO("快转·微传媒会员");
                    break;
                case 2:
                    userMembersVO.setMemberTypeVO("快点-扫码点餐会员");
                    break;
                case 3:
                    userMembersVO.setMemberTypeVO("快联-跨界盈利");
                    break;
                case 4:
                    userMembersVO.setMemberTypeVO("快销-商家促销");
                    break;
                case 5:
                    userMembersVO.setMemberTypeVO("快签-扫码签到");
                    break;
                case 6:
                    userMembersVO.setMemberTypeVO("快飞-梦想");
                    break;
                case 7:
                    userMembersVO.setMemberTypeVO("快推-城市");
                    break;
            }
            list.add(userMembersVO);
        }
        HttpServletResponse response = this.getResponse();
        //设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel");        //改成输出excel文件
        String fileName = "Order";
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

        //创建工作簿并发送到浏览器
        try {
            //创键Excel表格中的第一个表,命名为"第一页"
            WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
//第一sheet
            WritableSheet sheet = book.createSheet("订单详情", 0);
            //设置该单元格的表头
            List<String> keys = new ArrayList<>();
            keys.add("ID");
            keys.add("会员ID");
            keys.add("会员昵称");
            keys.add("会员电话");
            keys.add("会员类型");
            keys.add("结束时间");
            // 添加标题
            for (int x = 0; x < keys.size(); x++) {
                sheet.addCell((WritableCell) new Label(x, 0, keys.get(x)));
            }
            // 添加数据
            for (int y = 0; y < list.size(); y++) {
                sheet.addCell(new Label(0, y + 1, list.get(y).getMemberId().toString()));
                sheet.addCell(new Label(1, y + 1, list.get(y).getUserId().toString()));
                sheet.addCell(new Label(2, y + 1, list.get(y).getRemark()));
                sheet.addCell(new Label(3, y + 1, list.get(y).getPhoneVO()));
                sheet.addCell(new Label(4, y + 1, list.get(y).getMemberTypeVO()));
                sheet.addCell(new Label(5, y + 1, list.get(y).getEndTime()));
            }
            book.write();
            book.close();
        } catch (Exception e) {

        }
    }

}
